package com.dousb.cloudlibrary.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dousb.cloudlibrary.common.ErrorCode;
import com.dousb.cloudlibrary.constant.CommonConstant;
import com.dousb.cloudlibrary.exception.ThrowUtils;
import com.dousb.cloudlibrary.mapper.BookMapper;
import com.dousb.cloudlibrary.model.dto.book.BookQueryRequest;
import com.dousb.cloudlibrary.model.entity.Book;
import com.dousb.cloudlibrary.model.entity.User;
import com.dousb.cloudlibrary.model.vo.BookVO;
import com.dousb.cloudlibrary.model.vo.UserVO;
import com.dousb.cloudlibrary.service.BookService;
import com.dousb.cloudlibrary.service.UserService;
import com.dousb.cloudlibrary.utils.CacheUtil;
import com.dousb.cloudlibrary.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 图书表服务实现
 */
@Service
@Slf4j
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    private static final String RANKING_KEY = "library:book:ranking:by_isbn:30days";
    @Resource
    private UserService userService;
    @Resource
    private CacheUtil cacheUtil;

    /**
     * 校验数据
     *
     * @param book
     * @param add  对创建的数据进行校验
     */
    @Override
    public void validBook(Book book, boolean add) {
        ThrowUtils.throwIf(book == null, ErrorCode.PARAMS_ERROR);
        String book_name = book.getBook_name();
        String book_category = book.getBook_category();
        String book_isbn = book.getBook_isbn();
        String book_press = book.getBook_press();
        String book_author = book.getBook_author();
        Integer book_pagination = book.getBook_pagination();
        Double book_price = book.getBook_price();
        // 创建数据时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isBlank(book_name), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(book_isbn), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(book_press), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(book_author), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(book_category), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(book_pagination == null, ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(book_price == null, ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        if (StringUtils.isNotBlank(book_name)) {
            ThrowUtils.throwIf(book_name.length() > 32, ErrorCode.PARAMS_ERROR, "书名过长");
        }
        if (StringUtils.isNotBlank(book_isbn)) {
            ThrowUtils.throwIf(book_isbn.length() > 52, ErrorCode.PARAMS_ERROR, "ISBN号过长");
        }
        if (StringUtils.isNotBlank(book_press)) {
            ThrowUtils.throwIf(book_press.length() > 32, ErrorCode.PARAMS_ERROR, "出版社过长");
        }
        if (StringUtils.isNotBlank(book_author)) {
            ThrowUtils.throwIf(book_author.length() > 32, ErrorCode.PARAMS_ERROR, "作者过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param bookQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Book> getQueryWrapper(BookQueryRequest bookQueryRequest) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        if (bookQueryRequest == null) {
            return queryWrapper;
        }
        Long book_id = bookQueryRequest.getBook_id();
        String book_name = bookQueryRequest.getBook_name();
        String book_category = bookQueryRequest.getBook_category();
        String book_isbn = bookQueryRequest.getBook_isbn();
        String book_press = bookQueryRequest.getBook_press();
        String book_author = bookQueryRequest.getBook_author();
        String book_status = bookQueryRequest.getBook_status();
        String sortField = bookQueryRequest.getSortField();
        String sortOrder = bookQueryRequest.getSortOrder();
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(book_name), "book_name", book_name);
        queryWrapper.like(StringUtils.isNotBlank(book_category), "book_category", book_category);
        queryWrapper.like(StringUtils.isNotBlank(book_isbn), "book_isbn", book_isbn);
        queryWrapper.like(StringUtils.isNotBlank(book_press), "book_press", book_press);
        queryWrapper.like(StringUtils.isNotBlank(book_author), "book_author", book_author);
        queryWrapper.like(StringUtils.isNotBlank(book_status), "book_status", book_status);

        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(book_id), "book_id", book_id);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取图书表封装
     *
     * @param book
     * @param request
     * @return
     */
    @Override
    public BookVO getBookVO(Book book, HttpServletRequest request) {
        BookVO bookVO = BeanUtil.copyProperties(book, BookVO.class);
        // region 可选
        // 1. 关联查询用户信息
        User user = null;
        UserVO userVO = userService.getUserVO(user);
        bookVO.setUser(userVO);
        // endregion
        return bookVO;
    }

    /**
     * 分页获取图书表封装
     *
     * @param bookPage
     * @param request
     * @return
     */
    @Override
    public Page<BookVO> getBookVOPage(Page<Book> bookPage, HttpServletRequest request) {
        List<Book> bookList = bookPage.getRecords();
        Page<BookVO> bookVOPage = new Page<>(bookPage.getCurrent(), bookPage.getSize(), bookPage.getTotal());
        if (CollUtil.isEmpty(bookList)) {
            return bookVOPage;
        }
        List<BookVO> bookVOList = bookList.stream()
                .map(book -> getBookVO(book, request))
                .collect(Collectors.toList());
        bookVOPage.setRecords(bookVOList);
        return bookVOPage;
    }
}
